<?php

namespace app\admin\controller\wanlshop;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use app\common\library\Shangfutong;
use think\exception\PDOException;
use think\exception\ValidateException;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;

/**
 * 认证管理--店铺审核
 *
 * @icon fa fa-circle-o
 */
class Auth extends Backend
{
    
    /**
     * Auth模型对象
     * @var \app\admin\model\wanlshop\Auth
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wanlshop\Auth;
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("verifyList", $this->model->getVerifyList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
	/**
	 * 详情
	 */
	public function detail($ids = null)
	{
		$row = $this->model->get($ids);
		if (!$row) {
		    $this->error(__('No Results were found'));
		}
		$this->view->assign("row", $row);
		return $this->view->fetch();
	}

	/**
	 * 审核意见
	 */
	public function opinion($ids = null)
	{
		if ($this->request->isPost()) {
			$data=$this->request->post();
			$result=$this->model->where('id',$data['id'])->update(['refuse'=>$data['refuse']]);
			if ($result !== false) {
			    $this->success();
			} else {
			    $this->error(__('No rows were updated'));
			}
		}else{
			$row = $this->model->get($ids);
			if (!$row) {
				$this->error(__('No Results were found'));
			}
			$this->view->assign("row", $row);
		    return $this->view->fetch();
		}	
	}
	
	/**
	 * 同意
	 */
	public function agree($ids = null)
	{
		$row = $this->model->get($ids);
		if (!$row) {
		    $this->error(__('No Results were found'));
		}
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds)) {
		    if (!in_array($row[$this->dataLimitField], $adminIds)) {
		        $this->error(__('You have no permission'));
		    }
		}
		if ($row['verify'] == 3) {
		    // $this->error(__('已审核过本店铺，请不要重复审核！'));
		}
		if ($this->request->isPost()) {
			$result = false;
			Db::startTrans();
			try {
			    //是否采用模型验证
			    if ($this->modelValidate) {
			        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
			        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
			        $row->validateFailException(true)->validate($validate);
			    }

				// 商福通h5进件
				if(empty($row['applicationId'])){
					$data['applicationId']=rand(100000,999999).time();//用户申请单号
					$data['ifCode']='yspay';//通道编码
					$data['isvNo']='V20243693248574';//渠道号
					$data['range']='1';//0：线下；1：线上
					$data['notifyUrl']='https://hui.bianhui.shop/api/wanlshop/callback/notify_applyment/type/shangfutong';//回调地址
					$res=Shangfutong::applymentH5($data);
					if(isset($res["code"])&&$res["code"]=='000000'){
						$bizData=json_decode($res['bizData'],true);
						$applyment_h5 = $bizData["url"]??'';
					}
					$li['applyment_h5']=$applyment_h5;
				    $li['applicationId']=$data['applicationId'];
				}

				$li['verify']=3;
			    $result = $row->allowField(true)->save($li);
                
				// 审核通过
				if($row['verify'] != 4){
					
					// 插入店铺表
					$add_id = Db::name('WanlshopShop')->insertGetId([
						'shop_type' => $row['shop_type'],
						'user_id' => $row['user_id'],
						'state' => $row['state'],
						'shopname' => $row['shopname'],
						'avatar' => $row['avatar'],
						'bio' => $row['content'],
						'description' => $row['bio'],
						'city' => $row['city'],
						'area_code' => $row['area_code'],
						'verify' => $row['verify'],
						'application_id' => !empty($row['applicationId'])?$row['applicationId']:$li['applicationId']
					]);
				
					//生成收款二维码
					if(empty($row['pay_code_img'])){
						$qrCode = QrCode::create('https://hui.bianhui.shop?shop_type='.$row['shop_type'].'&shop_id='.$add_id);
						$writer = new PngWriter();
						$result = $writer->write($qrCode);
						$qr_img='img/qr/'.rand(111,999).time() . '.jpg';
						file_put_contents($qr_img, $result->getString());

						$result = Db::name('WanlshopShop')->where('id',$add_id)->update(['pay_code_img' => $qr_img]);
					}

					// // 经营信息
					// $data['merchantType']=1;//商户类型。1 - 小微商户；2 - 个体户；3 - 企业商户
					// $data['licenseImg']=1;//营业执照图片(小微商户不传)
					// $data['mchFullName']=$row['shopname'];//商户全称
					// $data['mchShortName']=$row['shopname'];//商户简称
					// $data['mccCode']=1;//经营类目
					// $data['areaCode']=1;//经营地址省市区编码
					// $data['address']=1;//商户经营地址
					// $data['storeOuterImg']=1;//门头照图片
					// $data['storeInnerImg']=1;//门店内景照片
					// $data['storeCashierImg']=1;//收银台照片
					// // 营业执照信息，小微商户不传
					// $data['contactName']=1;//联系人姓名
					// $data['contactPhone']=1;//联系人手机号
					// $data['contactEmail']=1;//联系人邮箱
					// // 结算信息
					// $data['settlementType']=1;//到账时间方式。T1、D1、D0
					// $data['settAccountType']=1;//结算账户类型，B：对公；C：对私(小微商户不支持对公)
					// $data['settAccountLicenseImg']=1;//结算银行卡图片(对私结算必传)
					// $data['companyAccountLicenseImg']=1;//开户许可证图片(对公结算必传)
					// $data['isUncrpSett']=1;//是否为同名结算。Y - 是；N - 否(对私结算必传)
					// $data['settAccountName']=1;//结算账户名(对私必传)
					// $data['settleAccountNo']=1;//结算账户号
					// $data['settAccountBankBranchAreaCode']=1;//开户行省市区编码
					// $data['settAccountBankBranchCode']=1;//开户行支行联行号
					// $data['settleAuthLetterPhoto']=1;//非 法人结算授权函
					// // 备用结算(非 法人结算,以及企业商户对私结算时必填)
					// $data['standByStlAccType']=1;//备用结算账户类型。B对公 C对私(企业商户必须是对公)
					// $data['standByStlAccCardImg']=1;//备用结算账户信息
					// $data['standByStlAccNo']=1;//备用结算账户号
					// $data['standByStlAccNm']=1;//备用结算账户名。(企业商户为营业执照名称；个体户商户为法人姓名)
					// $data['standByAccountBankBranchAreaCode']=1;//备用结算账户开户省市编码
					// $data['standByBankSubCode']=1;//备用结算信息开户行支行联行号
				}
			    Db::commit();
			} catch (ValidateException $e) {
			    Db::rollback();
			    $this->error($e->getMessage());
			} catch (PDOException $e) {
			    Db::rollback();
			    $this->error($e->getMessage());
			} catch (Exception $e) {
			    Db::rollback();
			    $this->error($e->getMessage());
			}
			if ($result !== false) {
			    $this->success();
			} else {
			    $this->error(__('No rows were updated'));
			}
		}
		$this->view->assign("row", $row);
		return $this->view->fetch();
	}
	
	/**
	 * 拒绝
	 */
	public function refuse($ids = null)
	{
		$row = $this->model->get($ids);
		if (!$row) {
		    $this->error(__('No Results were found'));
		}
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds)) {
		    if (!in_array($row[$this->dataLimitField], $adminIds)) {
		        $this->error(__('You have no permission'));
		    }
		}
		if ($this->request->isPost()) {
		    $params = $this->request->post("row/a");
		    if ($params) {
		        $params = $this->preExcludeFields($params);
		        $result = false;
		        Db::startTrans();
		        try {
		            //是否采用模型验证
		            if ($this->modelValidate) {
		                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
		                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
		                $row->validateFailException(true)->validate($validate);
		            }
					$params['verify'] = 4;
		            $result = $row->allowField(true)->save($params);
		            Db::commit();
		        } catch (ValidateException $e) {
		            Db::rollback();
		            $this->error($e->getMessage());
		        } catch (PDOException $e) {
		            Db::rollback();
		            $this->error($e->getMessage());
		        } catch (Exception $e) {
		            Db::rollback();
		            $this->error($e->getMessage());
		        }
		        if ($result !== false) {
		            $this->success();
		        } else {
		            $this->error(__('No rows were updated'));
		        }
		    }
		    $this->error(__('Parameter %s can not be empty', ''));
		}
		$this->view->assign("row", $row);
		return $this->view->fetch();
	}
	
}
